/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package diet.controller;

import diet.XMLUtils.XMLUltis;
import diet.dao.DAO;
import diet.dao.UserDAO;
import diet.dto.UserDTO;
import diet.XMLUtils.JAXB;
import diet.dao.DietDAO;
import diet.dao.DietDetailDAO;
import diet.dto.DietDTO;
import diet.dto.DishDTO;
import diet.dto.FoodDTO;
import diet.method.ControllerMethod;
import java.io.FileOutputStream;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.catalina.Session;

/**
 *
 * @author Vrety
 */
public class ControllerServlet extends HttpServlet {

    private int isFound = 0;
    private String inv = "Invalid username or passsword";
    private String suss = "Update Sussessful";
    private String fail = "Update Fail";
    private final String homePage = "home.jsp";
    private final String AdminPage = "admin.jsp";
    private final String LoginPage = "index.jsp";
    private final String SettingPage = "setting.jsp";
    private JAXB jaxb = null;
    private XMLUltis xu = null;
    private ControllerMethod cm = new ControllerMethod();

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String button = request.getParameter("btnAction");
            // String buttonajax = request.getParameter("btnActionAjax");
            if (button.equals("Login")) {

                String username = request.getParameter("txtUserName");
                String password = request.getParameter("txtPassword");
                String url = LoginPage;
                isFound = cm.checkLogin(username, password);
                if (isFound == 1) {
                    url = homePage;
                    HttpSession session = request.getSession();
                    session.setAttribute("FULLNAME", username);
                } else if (isFound == 2) {
                    url = AdminPage;
                    HttpSession session = request.getSession();
                    session.setAttribute("FULLNAME", username);
                } else if (isFound == 0) {

//                    HttpSession session = request.getSession();
                    request.setAttribute("INVALID", inv);
                }
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);
//                response.sendRedirect(url);

            } else if (button.equals("Logout")) {
                HttpSession session = request.getSession();
                session.invalidate();
                response.sendRedirect("home.jsp");
            } else if (button.equals("Show")) {
                UserDAO userdao = new UserDAO();
                ArrayList<UserDTO> results = new ArrayList<UserDTO>();
                results = userdao.show();
                HttpSession session = request.getSession();
                session.setAttribute("resultUser", results);
                request.getRequestDispatcher("manageUser.jsp").forward(request, response);

            } else if (button.equals("deleteUser")) {
                UserDAO userdao = new UserDAO();
                String id = request.getParameter("deleteValue");
                userdao.delete(Integer.parseInt(id));
                ArrayList<UserDTO> results = new ArrayList<UserDTO>();
                String searchname = request.getParameter("txtUserName");
                results = userdao.search(searchname);
                results = userdao.show();
                HttpSession session = request.getSession();
                session.setAttribute("resultUser", results);

                request.getRequestDispatcher("manageUser.jsp").forward(request, response);

            } else if (button.equals("SearchUser")) {
                UserDAO userdao = new UserDAO();
                ArrayList<UserDTO> results = new ArrayList<UserDTO>();
                String searchname = request.getParameter("txtUserName");
                results = userdao.search(searchname);

                HttpSession session = request.getSession();
                session.setAttribute("resultUser", results);
                request.getRequestDispatcher("manageUser.jsp").forward(request, response);

            } else if (button.equals("Register")) {
                String reg_email = request.getParameter("txtEmail");
                String reg_password = request.getParameter("txtPassword");
                UserDTO user = new UserDTO();
                user.setEmail(reg_email);
                user.setPassword(reg_password);
                HttpSession session = request.getSession();
                session.setAttribute("FULLNAME", reg_email);
                boolean result = new UserDAO().add(user);
                response.sendRedirect("home.jsp");
            } else if (button.equals("Test")) {
                if (XMLUltis.test(getServletContext().getRealPath("/"))) {
                    response.sendRedirect(getServletContext().getRealPath("/") + "xml/Dishes.pdf");
                }

            } else if (button.equals("CreatePDF")) {
                if (XMLUltis.createDishesPDF(getServletContext().getRealPath("/"))) {
                    response.sendRedirect("http://localhost:8080/DietPlanning/xml/Dishes.pdf");
                } else {
                    response.sendRedirect("manageDish.jsp");
                }

            } else if (button.equals("CreatePDFFood")) {
                if (XMLUltis.createFoodsPDF(getServletContext().getRealPath("/"))) {
                    response.sendRedirect("http://localhost:8080/DietPlanning/xml/Foods.pdf");
                } else {
                    response.sendRedirect("manageFood.jsp");
                }

            } else if (button.equals("ChangePassword")) {
                String currentPassword = request.getParameter("oldPassword");
                String Newpass = request.getParameter("newPassword");
                String customerEmail = request.getParameter("customerEmail");
                out.print(cm.changePassword(customerEmail, currentPassword, Newpass));
            } else if (button.equals("UpdateInformation")) {
                String customerName = request.getParameter("txtName");
                int male = Integer.parseInt(request.getParameter("sex"));
                String birthday = request.getParameter("birthday");
                int phone = Integer.parseInt(request.getParameter("phone"));
                int height = Integer.parseInt(request.getParameter("height"));
                int weight = Integer.parseInt(request.getParameter("weight"));
                HttpSession httpSession = request.getSession();
                String email = (String) httpSession.getAttribute("FULLNAME");
                out.print(cm.changeInfo(customerName, male, birthday, phone, height, weight, email));
                response.sendRedirect("setting.jsp");
            } else if (button.equals("SearchDish")) {
                String dishname = request.getParameter("txtDishName");
                xu = new XMLUltis();
                List<DishDTO> results = xu.searchDish(getServletContext().getRealPath("/"), dishname);
                //use session to save paging table
                HttpSession httpSession = request.getSession();
                httpSession.setAttribute("dishResults", results);
                //request.getRequestDispatcher("manageDish.jsp").forward(request, response);
                response.sendRedirect("manageDish.jsp");
            } else if (button.equals("SearchDishCus")) {
                String dishname = request.getParameter("txtDishName");
                xu = new XMLUltis();
                List<DishDTO> results = xu.searchDish(getServletContext().getRealPath("/"), dishname);
                //use session to save paging table
                HttpSession httpSession = request.getSession();
                httpSession.setAttribute("dishResults", results);
                //request.getRequestDispatcher("manageDish.jsp").forward(request, response);
                response.sendRedirect("dish.jsp");
            } else if (button.equals("SearchFood")) {
                String foodname = request.getParameter("txtFoodName");
                xu = new XMLUltis();
                ArrayList<FoodDTO> results = xu.searchFood(getServletContext().getRealPath("/"), foodname);
                HttpSession httpSession = request.getSession();
                httpSession.setAttribute("resultFood", results);

                response.sendRedirect("manageFood.jsp");
            } else if (button.equals("SearchFoodCus")) {
                String foodname = request.getParameter("txtFoodName");
                xu = new XMLUltis();
                ArrayList<FoodDTO> results = xu.searchFood(getServletContext().getRealPath("/"), foodname);
                HttpSession httpSession = request.getSession();
                httpSession.setAttribute("resultFood", results);

                response.sendRedirect("food.jsp");

            } else if (button.equals("mydiet")) {//NhuNHU
                HttpSession session = request.getSession();
                String username = (String) session.getAttribute("FULLNAME");
                UserDAO userDAO = new UserDAO();
                jaxb = new JAXB();
                int userid = userDAO.getUserByUsername(username).getUserID();
                //response.setContentType("text/xml");
                jaxb.generateDietPageXML(userid, getServletContext().getRealPath("/"));
                response.sendRedirect("diet.jsp");
            } else if (button.equals("SearchDiet")) {
                String dietname = request.getParameter("txtDietName");
                xu = new XMLUltis();
                ArrayList<DietDTO> results = xu.searchDiet(getServletContext().getRealPath("/"), dietname);
                HttpSession httpSession = request.getSession();
                httpSession.setAttribute("resultsDiet", results);
                request.getRequestDispatcher("manageDiet.jsp").forward(request, response);
            } else if (button.equals("viewDietDetail")) {//NhuNHU
                int dietID = Integer.parseInt(request.getParameter("id"));
                xu = new XMLUltis();
                //ArrayList
            } else if (button.equals("deleteDietDetail")) {
                int dietDetailID = Integer.parseInt(request.getParameter("dietDetailID"));
                DietDetailDAO dietDetailDAO = new DietDetailDAO();
                xu = new XMLUltis();
                boolean isDeleted = dietDetailDAO.delete(dietDetailID);
                if (isDeleted) {
                    xu.deleteDietDetailXMLFile(getServletContext().getRealPath("/") + "xml/DietInfo.xml", dietDetailID);
                    response.getWriter().write("Delete successfully");
                } else {
                    response.getWriter().write("Fail");
                }
            } else if (button.equals("Tạo thực đơn mới")) {//NhuNHU

                HttpSession session = request.getSession();
                String username = (String) session.getAttribute("FULLNAME");
                UserDAO userDAO = new UserDAO();
                cm.AutoGenerateMenu(username);
                int userid = userDAO.getUserByUsername(username).getUserID();
                jaxb = new JAXB();
                jaxb.generateDietPageXML(userid, getServletContext().getRealPath("/"));
                response.sendRedirect("diet.jsp");
            }
        } finally {
            out.close();
        }
    }

    private void generateFoodListXML() throws SQLException {
        DAO dao = new DAO();
        Connection con = dao.ConnectWithDriver();
        Statement pst = con.createStatement();
    }
    //// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);


    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";

    }// </editor-fold>
}
